import { createWebHistory, createRouter } from "vue-router";

import HomeView from "@/views/home/HomeView.vue";
import Login from "@/views/login/Login.vue";
import User from "../views/user/User.vue";
import Menu from "../views/menu/Menu.vue";
import Welcome from "../views/welcome/Welcome.vue";

const routes = [
  { path: "/", redirect: "/login" },
  { path: "/login", component: Login },
  {
    path: "/home",
    component: HomeView,
    meta: { requiresAuth: true }, // 使用meta字段标记该路由需要认证
    children: [
      {
        path: "/welcome",
        component: Welcome,
      },
      {
        path: "/users",
        component: User,
      },
      {
        path: "/menus",
        component: Menu,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  // 检查是否需要登录访问的路由
  const isAuthenticated = checkAuthentication(); // 这是一个假设的函数，你应该在这里实现你的登录状态检查逻辑
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    // 该路由需要认证，但用户未登录
    next({ path: '/login'}); // 重定向到登录页面，并携带之前的路径信息
  } else {
    next(); // 确保一定要调用 next()
  }
});

function checkAuthentication() {
  console.log(!!localStorage.getItem('token'))
  // 这里应该检查用户的登录状态，例如检查localStorage, sessionStorage或者Vuex状态等
  return !!localStorage.getItem('token'); // 示例：检查localStorage中是否存在用户token
}


export default router;
